# -*- coding: utf-8 -*-
# File : app.py
# Author: taoyahui
# Date : 2022/5/30

from flask import Flask, request, render_template
import forms
import sqlite3

app = Flask(__name__) # 创建一个Flask对象

def execSQL(sql):
    conn = sqlite3.connect('blog.db')
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        conn.commit()
        return result
    except BaseException as e:
        conn.rollback()
        print ('错误: %s' % e)
    finally:
        conn.close()


@app.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(username, password)
        user = execSQL(f"select * from user where username = '{username}'")
        if user[0][1] == password:
            blogs = execSQL("select id, title from blogs")
            return render_template("blog_list.html", blogs=blogs)
        else:
            return render_template("login.html", msg="账户或密码错误!")
    else:
        return render_template("login.html")


@app.route('/')
def index():
    blogs = execSQL("select id, title from blogs")
    return render_template("blog_list.html", blogs=blogs)


@app.route("/blog/<blog_id>")
def blog(blog_id):
    blog = execSQL("select * from blogs where id = %s" % blog_id)
    print(blog)
    if blog:
        return render_template("blog.html", blog=blog[0])
    return "<a href='/'>博客未找到！点击回到目录</a>"


if __name__ == '__main__':
    app.run(host='0.0.0.0')
